package com.tycmc.signelectroniccontracts.tools.net;

import android.app.Activity;

import com.tycmc.signelectroniccontracts.R;
import com.tycmc.signelectroniccontracts.entity.PDFPositionEntity;
import com.tycmc.signelectroniccontracts.tools.base.FraBase;
import com.tycmc.signelectroniccontracts.tools.images.UrlPath;
import com.tycmc.signelectroniccontracts.tools.net.proces.ProgressHelper;
import com.tycmc.signelectroniccontracts.tools.net.proces.UIProgressRequestListener;
import com.tycmc.signelectroniccontracts.tools.net.result.DownResult;
import com.tycmc.signelectroniccontracts.tools.net.result.DownResultPDF;
import com.tycmc.signelectroniccontracts.tools.net.result.NetworkResult;
import com.tycmc.signelectroniccontracts.tools.net.result.ProGressUpDataListen;
import com.tycmc.signelectroniccontracts.tools.net.tools.Json;
import com.tycmc.signelectroniccontracts.tools.net.tools.NetUtils;
import com.tycmc.signelectroniccontracts.tools.other.TextShow;
import com.tycmc.signelectroniccontracts.tools.show.LogShow;
import com.tycmc.signelectroniccontracts.tools.store.DBHelper;
import com.tycmc.signelectroniccontracts.tools.store.SharePre;
import com.tycmc.signelectroniccontracts.tools.store.SharePreName;

import org.json.JSONException;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by Administrator on 2017/2/20 0020.
 */

public class NetWorkUtils {
    private String noNetWork;
    private String noJson;
    private Activity context;
    private FraBase fragment;

    public NetWorkUtils(Activity context) {
        this.context = context;
        noNetWork = context.getString(R.string.no_network);
        noJson = context.getString(R.string.no_isjson);
    }

    public NetWorkUtils(FraBase fragment) {
        this.fragment = fragment;
        context = fragment.getActivity();
        noNetWork = context.getString(R.string.no_network);
        noJson = context.getString(R.string.no_isjson);
    }

    public void post(RequestAction requestAction, final NetworkResult result) {
        if (NetUtils.networkTest(context)) {
            final String netUrl = requestAction.netUrl;
            Map<String, String> headerMap = requestAction.headerMap;
            Map<String, Object> requestMap = requestAction.requestMap;
            String contentType = requestAction.contentType;

            FormBody.Builder builder = new FormBody.Builder();
            String postData = Json.getJsonStr(requestMap);
            String headerPost = Json.getJsonStr(headerMap);

            if (requestMap != null && requestMap.size() != 0) {
                Set<String> set = requestMap.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    builder.add(next, Json.getJsonStr(requestMap.get(next)));
                }
            }
            Request.Builder post = new Request.Builder()
                    .url(netUrl);
            if (contentType.equals(requestAction.APPLICATIONJSON)) {//请求方式为application形式的
                RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postData);
                post = post.post(formBody);
            } else {
                FormBody formBody = builder.build();
                post = post.post(formBody);
            }
            if (headerMap != null && headerMap.size() != 0) {
                Set<String> set = headerMap.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    post.header(next, headerMap.get(next));
                }
            }
            Request request = post
                    .build();


            LogShow.i("网络请求post", "请求地址：" + netUrl
                    + "\nContent-Type:" + contentType
                    + "\nHeader：" + headerPost
                    + "\nBody：" + postData);

            OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).connectTimeout(60, TimeUnit.SECONDS).build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    LogShow.i("网络请求post失败" + netUrl, e.getMessage());
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            failed(result, e.getMessage());
                        }
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String strJson = response.body().string();
                    LogShow.i("网络请求post成功" + netUrl, strJson);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sucess(result, Json.getMap(strJson), strJson);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                failed(result, e.getMessage());
                            }
                        }
                    });


                }
            });
        } else {
            failed(result, noNetWork);
        }
    }

    public void postJson(RequestAction requestAction, final NetworkResult result) {
        if (NetUtils.networkTest(context)) {
            final String netUrl = NetUrl.netHead + requestAction.netUrl;
            Map<String, String> headerMap = requestAction.headerMap;
            Map<String, Object> requestMap = requestAction.requestMap;
            String contentType = requestAction.contentType;
            headerMap.put("Authorization", SharePre.getString(SharePreName.TOKEN, ""));
            FormBody.Builder builder = new FormBody.Builder();
            String postData = Json.getJsonStr(requestMap);
            String headerPost = Json.getJsonStr(headerMap);

            if (requestMap != null && requestMap.size() != 0) {
                Set<String> set = requestMap.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    builder.add(next, Json.getJsonStr(requestMap.get(next)));
                }
            }
            Request.Builder post = new Request.Builder()
                    .url(netUrl);
            RequestBody formBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), postData);
            post = post.post(formBody);
            if (headerMap != null && headerMap.size() != 0) {
                Set<String> set = headerMap.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    post.header(next, headerMap.get(next));
                }
            }
            Request request = post
                    .build();


            LogShow.i("网络请求post", "请求地址：" + netUrl
                    + "\nContent-Type:" + contentType
                    + "\nHeader：" + headerPost
                    + "\nBody：" + postData);

            OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).connectTimeout(60, TimeUnit.SECONDS).build();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    LogShow.i("网络请求post失败" + netUrl, e.getMessage());
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            failed(result, e.getMessage());
                        }
                    });

                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String strJson = response.body().string();
                    LogShow.i("网络请求post成功" + netUrl, strJson);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sucessJson(result, Json.getMap(strJson), strJson);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                failed(result, e.getMessage());
                            }
                        }
                    });


                }
            });
        } else {
            failed(result, noNetWork);
        }
    }

    /**
     * get请求
     */
    public void getRequest(final RequestAction requestAction, final NetworkResult result) {
        if (NetUtils.networkTest(context)) {
            Map<String, Object> paramMap = requestAction.requestMap;
            FormBody.Builder builder = new FormBody.Builder();
            String netUrl = requestAction.netUrl;
            if (paramMap != null && paramMap.size() != 0) {
                Set<String> set = paramMap.keySet();
                Iterator<String> iterator = set.iterator();
                while (iterator.hasNext()) {
                    String next = iterator.next();
                    builder.add(next, String.valueOf(paramMap.get(next)));
                    netUrl = netUrl + next + "=" + paramMap.get(next) + "&";
                }
            }
            String subNetUrl = netUrl;
            if (netUrl.endsWith("&")) {
                subNetUrl = netUrl.substring(0, netUrl.length() - 1);
            }
            Request request = new Request.Builder()
                    .url(subNetUrl).get()
                    .addHeader("Authorization", SharePre.getString(SharePreName.token_type, "") + " " + SharePre.getString(SharePreName.TOKEN, ""))
                    .build();
            OkHttpClient client = new OkHttpClient().newBuilder().readTimeout(60, TimeUnit.SECONDS).writeTimeout(60, TimeUnit.SECONDS).connectTimeout(60, TimeUnit.SECONDS).build();
            Call call = client.newCall(request);
            LogShow.i("get请求", subNetUrl);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    LogShow.i("get请求失败", e.getMessage());
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            failed(result, e.getMessage());
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String strJson = response.body().string();
                    LogShow.i("get请求成功", strJson);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sucess(result, Json.getMap(strJson), strJson);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                failed(result, e.getMessage());
                            }

                        }
                    });
                }
            });
        } else {
            result.failed(noNetWork);
        }
    }


    /**
     * 文件下载
     */
    public void downLoadFile1(RequestAction requestAction, final DownResult result) {
        if (NetUtils.networkTest(context)) {

            final File file = new File(UrlPath.CrashLog + requestAction.netUrl.hashCode());
            final Request request = new Request.Builder().url(requestAction.netUrl).build();
            OkHttpClient okHttpClient = new OkHttpClient();
            final Call call = okHttpClient.newCall(request);
            okHttpClient.newBuilder().readTimeout(60, TimeUnit.SECONDS);
            okHttpClient.newBuilder().writeTimeout(60, TimeUnit.SECONDS);
            okHttpClient.newBuilder().connectTimeout(60, TimeUnit.SECONDS);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            result.downfail(e.getMessage());
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    try {
                        final long total = response.body().contentLength();
                        long current = 0;
                        is = response.body().byteStream();
                        fos = new FileOutputStream(file);
                        while ((len = is.read(buf)) != -1) {
                            current += len;
                            fos.write(buf, 0, len);
                            final long finalCurrent = current;
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    result.downsucess(finalCurrent, total, false);
                                }
                            });
                        }
                        fos.flush();
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                        final long finalCurrent1 = current;
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                result.downsucess(finalCurrent1, total, true);
                                result.sucess(file);
                            }
                        });
                    } catch (IOException e) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                result.downfail("文件下载失败，请重试");
                            }
                        });
                    }
                }
            });
        } else {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.downfail(noNetWork);
                }
            });
        }
    }

    /**
     * 下载多个文件，分别保存在本地
     *
     * @param requestAction
     * @param result
     */
    public void downLoadPDF(final RequestAction requestAction, final DownResultPDF result) {
        if (NetUtils.networkTest(context)) {

//            final File file = (File) requestAction.requestMap.get("file");
            if (requestAction.netUrl == null) {
                result.downfail("失败");
                return;
            }
            final Request request = new Request.Builder().url(requestAction.netUrl).build();
            OkHttpClient okHttpClient = new OkHttpClient();
            final Call call = okHttpClient.newCall(request);
            okHttpClient.newBuilder().readTimeout(60, TimeUnit.SECONDS);
            okHttpClient.newBuilder().writeTimeout(60, TimeUnit.SECONDS);
            okHttpClient.newBuilder().connectTimeout(60, TimeUnit.SECONDS);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            result.downfail(e.getMessage());
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    try {
                        final long total = response.body().contentLength();
                        long current = 0;
                        is = response.body().byteStream();
                        int i = 0;
                        final List<File> list = new ArrayList<>();
                        //清空PDF文件关联的名字
                        DBHelper.delete(context, requestAction.netUrl.hashCode() + "");
                        while ((len = is.read(buf)) != -1) {
                            current += len;
//                            将PDF关联的文件的名字读取保存在数据库中
                            PDFPositionEntity entity = new PDFPositionEntity();
                            entity.setOrdernum(i);
                            entity.setPosition(requestAction.netUrl.hashCode() + "");
                            entity.setUrlpath(UrlPath.CrashLog + requestAction.netUrl.hashCode() + System.currentTimeMillis() + i);
                            DBHelper.save(context, entity);
                            File name = new File(entity.getUrlpath());
                            i++;
                            list.add(name);
                            FileOutputStream fos = new FileOutputStream(name);
                            fos.write(buf, 0, len);
                            final long finalCurrent = current;
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {

                                    result.downsucess(finalCurrent, total, false);
                                }
                            });
                            fos.flush();
                            if (fos != null) {
                                fos.close();
                            }
                        }
                        if (is != null) {
                            is.close();
                        }

                        final long finalCurrent1 = current;
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                result.downsucess(finalCurrent1, total, true);
                                File[] files = new File[list.size()];
                                for (int j = 0; j < list.size(); j++) {
                                    files[j] = list.get(j);
                                }
                                //当fragment进行网络请求且fragment已被销毁，将停止网络返回
                                if (fragment != null && fragment.isDetached()) {
                                    return;
                                }
                                //当activity 被销毁后，网络请求不在返回
                                if (context.isDestroyed()) {
                                    return;
                                }
                                result.sucess(files);
                            }
                        });
                    } catch (Exception e) {
                        LogShow.i("错误日志", e.getMessage());
                        if (is != null) {
                            is.close();
                        }
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                //当fragment进行网络请求且fragment已被销毁，将停止网络返回
                                if (fragment != null && fragment.isDetached()) {
                                    return;
                                }
                                //当activity 被销毁后，网络请求不在返回
                                if (context.isDestroyed()) {
                                    return;
                                }
                                result.downfail("文件下载失败，请重试");
                            }
                        });
                    }
                }
            });
        } else {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.downfail(noNetWork);
                }
            });
        }
    }

    /**
     * 带有上传进度的上传
     *
     * @param action
     * @param callBack
     */
    public void upLoadProgress(RequestAction action, final ProGressUpDataListen callBack) {


        if (!NetUtils.networkTest(context)) {
            failed(callBack, noNetWork);
            return;
        }
        try {
            String requestUrl = NetUrl.netHead + action.netUrl;
            MultipartBody.Builder builder = new MultipartBody.Builder("Aa");
            //设置类型
            builder.setType(MultipartBody.FORM);
            Map<String, Object> requestMap = action.requestMap;
            for (String key : requestMap.keySet()) {
                Object object = requestMap.get(key);
                if (object instanceof File[]) {
                    File[] files = (File[]) object;
                    for (int i = 0; i < files.length; i++) {
                        File file = files[i];
                        String absolutePath = file.getAbsolutePath();
                        String substring = absolutePath.substring(absolutePath.lastIndexOf("/"));
                        builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("*/*"), file));

                    }
                } else if (!(object instanceof File)) {
                    builder.addFormDataPart(key, String.valueOf(object));
                } else {
                    File file = (File) object;
                    String absolutePath = file.getAbsolutePath();
//                    String substring = absolutePath.substring(absolutePath.lastIndexOf("/"));
                    builder.addFormDataPart(key, file.getName(), RequestBody.create(MediaType.parse("*/*"), file));
//                    builder.addPart(Headers.of("Content-Disposition", "form-data; filename=\"" + substring + "\""),
//                            RequestBody.create(MediaType.parse("*/*"), file));
                }
            }
            //这个是ui线程回调，可直接操作UI
            UIProgressRequestListener uiProgressRequestListener = new UIProgressRequestListener() {
                @Override
                public void onUIRequestProgress(long bytesWrite, long contentLength, boolean done) {
                    callBack.onRequestProgress(bytesWrite, contentLength, done);
                }
            };

            LogShow.i("网络请求post", "请求地址：" + requestUrl
                    + "\nBody：" + requestMap);
            //创建RequestBody
            RequestBody body = builder.build();
            Request request = new Request.Builder()
                    .url(requestUrl)
                    .addHeader("Authorization", SharePre.getString(SharePreName.TOKEN, ""))
                    .post(ProgressHelper.addProgressRequestListener(body, uiProgressRequestListener)).build();
            OkHttpClient.Builder newBuilder = new OkHttpClient().newBuilder();
            newBuilder.writeTimeout(50, TimeUnit.SECONDS);
            newBuilder.connectTimeout(60, TimeUnit.MINUTES);
            newBuilder.readTimeout(60, TimeUnit.MINUTES);
            Call call = newBuilder.build().newCall(request);
            //开始请求
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            failed(callBack, e.getMessage());
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    final String strJson = response.body().string();
                    LogShow.i("网络请求成功",strJson);
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            try {
                                sucessJsonUpdata(callBack, Json.getMap(strJson), strJson);
                            } catch (JSONException e) {
                                e.printStackTrace();
                                failed(callBack, e.getMessage());
                            }

                        }
                    });
                }
            });
        } catch (Exception e) {
        }

    }

    /**
     * 普通网络请求失败后统一返回值
     *
     * @param result 接口回调
     * @param o      失败原因
     */
    public void failed(NetworkResult result, Object o) {
        //当fragment进行网络请求且fragment已被销毁，将停止网络返回
        if (fragment != null && fragment.isDetached()) {
            return;
        }
        //当activity 被销毁后，网络请求不在返回
        if (context.isDestroyed()) {
            return;
        }
        result.failed(o);
    }

    /**
     * 普通网络请求失败后统一返回值
     *
     * @param result 接口回调
     * @param o      失败原因
     */
    public void failed(ProGressUpDataListen result, Object o) {
        //当fragment进行网络请求且fragment已被销毁，将停止网络返回
        if (fragment != null && fragment.isDetached()) {
            return;
        }
        //当activity 被销毁后，网络请求不在返回
        if (context.isDestroyed()) {
            return;
        }
        result.failed(o);
    }

    /**
     * Post请求成功后调用的方法
     *
     * @param result  回调接口
     * @param data    Map对象
     * @param jsonStr 原有Json
     */
    public void sucessJson(NetworkResult result, Map data, String jsonStr) {
        //当fragment进行网络请求且fragment已被销毁，将停止网络返回
        if (fragment != null && fragment.isDetached()) {
            return;
        }
        //当activity 被销毁后，网络请求不在返回
        if (context != null && context.isDestroyed()) {
            return;
        }
        if (String.valueOf(data.get("status")).equals("200")) {
            if (data.get("info") instanceof Map) {
                Map info = (Map) data.get("info");
                if(TextShow.valueOf(info.get("code")).equals("0")){
                    if (data.get("data") instanceof Map) {
                        result.sucess((Map<String, Object>) data.get("data"), jsonStr);
                    } else {
                        Map map = new HashMap();
                        map.put("data", data.get("data"));
                        result.sucess(map, jsonStr);
                    }
                }else {
                    result.failed(info.get("message"));
                }

            } else {
                result.failed(data.get("info"));

            }

        } else {
            if (data.get("info") instanceof Map) {
                result.failed(((Map) data.get("info")).get("developMessage"));
            } else {
                result.failed(data.get("info"));

            }
        }

    }

    public void sucess(NetworkResult result, Map data, String jsonStr) {
        //当fragment进行网络请求且fragment已被销毁，将停止网络返回
        if (fragment != null && fragment.isDetached()) {
            return;
        }
        //当activity 被销毁后，网络请求不在返回
        if (context != null && context.isDestroyed()) {
            return;
        }
        result.sucess(data, jsonStr);


    }

    /**
     * Post请求成功后调用的方法
     *
     * @param result  回调接口
     * @param data    Map对象
     * @param jsonStr 原有Json
     */
    public void sucess(ProGressUpDataListen result, Map data, String jsonStr) {
        //当fragment进行网络请求且fragment已被销毁，将停止网络返回
        if (fragment != null && fragment.isDetached()) {
            return;
        }
        //当activity 被销毁后，网络请求不在返回
        if (context.isDestroyed()) {
            return;
        }

        result.sucess(data, jsonStr);
    }

    public void sucessJsonUpdata(ProGressUpDataListen result, Map data, String jsonStr) {
        //当fragment进行网络请求且fragment已被销毁，将停止网络返回
        if (fragment != null && fragment.isDetached()) {
            return;
        }
        //当activity 被销毁后，网络请求不在返回
        if (context != null && context.isDestroyed()) {
            return;
        }
        if (String.valueOf(data.get("status")).equals("200")) {
            if (data.get("info") instanceof Map) {
                Map info = (Map) data.get("info");
                if(TextShow.valueOf(info.get("code")).equals("0")){
                    if (data.get("data") instanceof Map) {
                        result.sucess((Map<String, Object>) data.get("data"), jsonStr);
                    } else {
                        Map map = new HashMap();
                        map.put("data", data.get("data"));
                        result.sucess(map, jsonStr);
                    }
                }else {
                    result.failed(info.get("message"));
                }

            } else {
                result.failed(data.get("info"));

            }

        } else {
            if (data.get("info") instanceof Map) {
                result.failed(((Map) data.get("info")).get("developMessage"));
            } else {
                result.failed(data.get("info"));

            }
        }

    }


    /**
     * 文件下载
     */
    public Call downLoadFile(RequestAction requestAction, final DownResult result) {

        if (NetUtils.networkTest(context)) {

//            final File file = (File) requestAction.requestMap.get("file");
            final File file = new File(UrlPath.CrashLog + requestAction.netUrl.hashCode());
            final Request request = new Request.Builder().url(requestAction.netUrl).build();
            OkHttpClient okHttpClient = new OkHttpClient();
            final Call call = okHttpClient.newCall(request);
            okHttpClient.newBuilder().readTimeout(60, TimeUnit.SECONDS);
            okHttpClient.newBuilder().writeTimeout(60, TimeUnit.SECONDS);
            okHttpClient.newBuilder().connectTimeout(60, TimeUnit.SECONDS);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Call call, final IOException e) {
                    context.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            result.downfail(e.getMessage());
                        }
                    });
                }

                @Override
                public void onResponse(Call call, Response response) throws IOException {
                    InputStream is = null;
                    byte[] buf = new byte[2048];
                    int len = 0;
                    FileOutputStream fos = null;
                    try {
                        final long total = response.body().contentLength();
                        long current = 0;
                        is = response.body().byteStream();
                        fos = new FileOutputStream(file);
                        while ((len = is.read(buf)) != -1) {
                            current += len;
                            fos.write(buf, 0, len);
                            final long finalCurrent = current;
                            context.runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    result.downsucess(finalCurrent, total, false);
                                }
                            });
                        }
                        fos.flush();
                        if (is != null) {
                            is.close();
                        }
                        if (fos != null) {
                            fos.close();
                        }
                        final long finalCurrent1 = current;
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                result.downsucess(finalCurrent1, total, true);
                                result.sucess(file);
                            }
                        });
                    } catch (IOException e) {
                        context.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                result.downfail("文件下载失败，请重试");
                            }
                        });
                    }
                }
            });
            return call;
        } else {
            context.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    result.downfail(noNetWork);
                }
            });
        }
        return null;
    }
}
